package com.social.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @Author: XiaoXu
 * @Description:
 * @Date: Created in 21:17 2022/9/29
 * @Modified By:
 * @Version: 1.0
 */

@Component
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final long BEGIN_SECOND = 1664487267L;

    /**
        * 后32位为自增位
    */
    private static final Integer COUNT_BITS = 32;

    public long nexId(String keyPreFix) {
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long dateTemp = nowSecond - BEGIN_SECOND;

        //2.生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        String key = "activity:" + keyPreFix + ":" + date;
        Long count = stringRedisTemplate.opsForValue().increment(key);
        stringRedisTemplate.expire(key , 30L, TimeUnit.MINUTES);
        //3.拼接返回
        return dateTemp << COUNT_BITS | count;
    }


}
